<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  Progress,
  Row,
  Space,
  Statistic,
  Tag,
} from 'ant-design-vue';

// 监控数据接口
interface MonitoringData {
  timestamp: string;
  onlineRate: number;
  responseTime: number;
  errorRate: number;
  activeAlerts: number;
}

// 设备分类统计
interface CategoryStats {
  name: string;
  total: number;
  online: number;
  offline: number;
  error: number;
  icon: string;
  color: string;
}

const props = defineProps<{
  refreshInterval?: number;
}>();

// 监控数据
const monitoringData = ref<MonitoringData>({
  timestamp: new Date().toLocaleString(),
  onlineRate: 92.5,
  responseTime: 150,
  errorRate: 2.1,
  activeAlerts: 8,
});

// 设备分类统计
const categoryStats = ref<CategoryStats[]>([
  {
    name: '门锁',
    total: 45,
    online: 42,
    offline: 2,
    error: 1,
    icon: 'ant-design:lock-outlined',
    color: '#1890ff',
  },
  {
    name: '水电表',
    total: 32,
    online: 30,
    offline: 1,
    error: 1,
    icon: 'ant-design:thunderbolt-outlined',
    color: '#52c41a',
  },
  {
    name: '摄像头',
    total: 28,
    online: 26,
    offline: 2,
    error: 0,
    icon: 'ant-design:camera-outlined',
    color: '#722ed1',
  },
  {
    name: '传感器',
    total: 25,
    online: 24,
    offline: 1,
    error: 0,
    icon: 'ant-design:radar-chart-outlined',
    color: '#fa8c16',
  },
  {
    name: '控制器',
    total: 18,
    online: 17,
    offline: 1,
    error: 0,
    icon: 'ant-design:control-outlined',
    color: '#13c2c2',
  },
]);

// 实时告警
const realtimeAlerts = ref([
  {
    id: '1',
    level: 'critical',
    title: '门锁离线',
    device: '智能门锁-101',
    time: '2分钟前',
  },
  {
    id: '2',
    level: 'warning',
    title: '水电表异常',
    device: '水表-205',
    time: '5分钟前',
  },
  {
    id: '3',
    level: 'info',
    title: '设备重启',
    device: '摄像头-大厅',
    time: '10分钟前',
  },
]);

// 性能指标
const performanceMetrics = ref({
  cpu: 45,
  memory: 68,
  network: 32,
  storage: 78,
});

// 获取告警级别颜色
const getAlertLevelColor = (level: string) => {
  const colors = {
    critical: 'red',
    warning: 'orange',
    info: 'blue',
  };
  return colors[level] || 'default';
};

// 获取告警级别文本
const getAlertLevelText = (level: string) => {
  const texts = {
    critical: '严重',
    warning: '警告',
    info: '信息',
  };
  return texts[level] || level;
};

// 获取响应时间状态
const getResponseTimeStatus = (time: number) => {
  if (time < 100) return { color: '#52c41a', text: '优秀' };
  if (time < 200) return { color: '#faad14', text: '良好' };
  if (time < 500) return { color: '#fa8c16', text: '一般' };
  return { color: '#f5222d', text: '较差' };
};

// 获取错误率状态
const getErrorRateStatus = (rate: number) => {
  if (rate < 1) return { color: '#52c41a', text: '优秀' };
  if (rate < 3) return { color: '#faad14', text: '良好' };
  if (rate < 5) return { color: '#fa8c16', text: '一般' };
  return { color: '#f5222d', text: '较差' };
};

// 刷新数据
const refreshData = () => {
  // 模拟数据更新
  monitoringData.value = {
    timestamp: new Date().toLocaleString(),
    onlineRate: Math.random() * 10 + 90,
    responseTime: Math.random() * 200 + 100,
    errorRate: Math.random() * 3 + 1,
    activeAlerts: Math.floor(Math.random() * 10) + 5,
  };
};

// 自动刷新
let refreshTimer: NodeJS.Timeout | null = null;
letrefreshTimer;

onMounted(() => {
  if (props.refreshInterval) {
    refreshTimer = setInterval(refreshData, props.refreshInterval);
  }
});

// 组件卸载时清理定时器
const onUnmounted = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
};
</script>

<template>
  <div class="device-dashboard">
    <!-- 实时监控指标 -->
    <Row :gutter="16" class="metrics-row">
      <Col :span="6">
        <Card class="metric-card">
          <Statistic
            title="设备在线率"
            :value="monitoringData.onlineRate"
            :precision="1"
            suffix="%"
            :value-style="{ color: '#52c41a' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:check-circle-outlined" />
            </template>
          </Statistic>
          <Progress
            :percent="monitoringData.onlineRate"
            :show-info="false"
            stroke-color="#52c41a"
            size="small"
          />
        </Card>
      </Col>
      <Col :span="6">
        <Card class="metric-card">
          <Statistic
            title="平均响应时间"
            :value="monitoringData.responseTime"
            suffix="ms"
            :value-style="{
              color: getResponseTimeStatus(monitoringData.responseTime).color,
            }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:clock-circle-outlined" />
            </template>
          </Statistic>
          <div class="metric-status">
            <Tag
              :color="getResponseTimeStatus(monitoringData.responseTime).color"
            >
              {{ getResponseTimeStatus(monitoringData.responseTime).text }}
            </Tag>
          </div>
        </Card>
      </Col>
      <Col :span="6">
        <Card class="metric-card">
          <Statistic
            title="错误率"
            :value="monitoringData.errorRate"
            :precision="1"
            suffix="%"
            :value-style="{
              color: getErrorRateStatus(monitoringData.errorRate).color,
            }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:exclamation-circle-outlined" />
            </template>
          </Statistic>
          <div class="metric-status">
            <Tag :color="getErrorRateStatus(monitoringData.errorRate).color">
              {{ getErrorRateStatus(monitoringData.errorRate).text }}
            </Tag>
          </div>
        </Card>
      </Col>
      <Col :span="6">
        <Card class="metric-card">
          <Statistic
            title="活跃告警"
            :value="monitoringData.activeAlerts"
            :value-style="{ color: '#f5222d' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:alert-outlined" />
            </template>
          </Statistic>
          <div class="metric-status">
            <Button type="link" size="small">查看详情</Button>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 设备分类统计 -->
    <Row :gutter="16" class="category-row">
      <Col v-for="category in categoryStats" :key="category.name" :span="4">
        <Card class="category-card" :hoverable="true">
          <div class="category-header">
            <IconifyIcon
              :icon="category.icon"
              :style="{ color: category.color }"
              class="category-icon"
            />
            <span class="category-name">{{ category.name }}</span>
          </div>
          <div class="category-stats">
            <div class="stat-item">
              <span class="stat-label">总数:</span>
              <span class="stat-value">{{ category.total }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">在线:</span>
              <span class="stat-value online">{{ category.online }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">离线:</span>
              <span class="stat-value offline">{{ category.offline }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">故障:</span>
              <span class="stat-value error">{{ category.error }}</span>
            </div>
          </div>
          <div class="category-progress">
            <Progress
              :percent="Math.round((category.online / category.total) * 100)"
              :show-info="false"
              :stroke-color="category.color"
              size="small"
            />
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 实时告警和性能监控 -->
    <Row :gutter="16" class="monitoring-row">
      <Col :span="12">
        <Card title="实时告警" class="alerts-card">
          <div class="alerts-list">
            <div
              v-for="alert in realtimeAlerts"
              :key="alert.id"
              class="alert-item"
            >
              <div class="alert-info">
                <Tag :color="getAlertLevelColor(alert.level)">
                  {{ getAlertLevelText(alert.level) }}
                </Tag>
                <span class="alert-title">{{ alert.title }}</span>
              </div>
              <div class="alert-details">
                <span class="alert-device">{{ alert.device }}</span>
                <span class="alert-time">{{ alert.time }}</span>
              </div>
            </div>
          </div>
          <div class="alerts-footer">
            <Button type="link" size="small">查看全部告警</Button>
          </div>
        </Card>
      </Col>
      <Col :span="12">
        <Card title="系统性能" class="performance-card">
          <div class="performance-metrics">
            <div class="performance-item">
              <div class="performance-header">
                <span class="performance-label">CPU使用率</span>
                <span class="performance-value"
                  >{{ performanceMetrics.cpu }}%</span
                >
              </div>
              <Progress
                :percent="performanceMetrics.cpu"
                :show-info="false"
                :stroke-color="
                  performanceMetrics.cpu > 80 ? '#f5222d' : '#52c41a'
                "
              />
            </div>
            <div class="performance-item">
              <div class="performance-header">
                <span class="performance-label">内存使用率</span>
                <span class="performance-value"
                  >{{ performanceMetrics.memory }}%</span
                >
              </div>
              <Progress
                :percent="performanceMetrics.memory"
                :show-info="false"
                :stroke-color="
                  performanceMetrics.memory > 80 ? '#f5222d' : '#52c41a'
                "
              />
            </div>
            <div class="performance-item">
              <div class="performance-header">
                <span class="performance-label">网络使用率</span>
                <span class="performance-value"
                  >{{ performanceMetrics.network }}%</span
                >
              </div>
              <Progress
                :percent="performanceMetrics.network"
                :show-info="false"
                :stroke-color="
                  performanceMetrics.network > 80 ? '#f5222d' : '#52c41a'
                "
              />
            </div>
            <div class="performance-item">
              <div class="performance-header">
                <span class="performance-label">存储使用率</span>
                <span class="performance-value"
                  >{{ performanceMetrics.storage }}%</span
                >
              </div>
              <Progress
                :percent="performanceMetrics.storage"
                :show-info="false"
                :stroke-color="
                  performanceMetrics.storage > 80 ? '#f5222d' : '#52c41a'
                "
              />
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 更新时间 -->
    <div class="update-time">
      <Space>
        <IconifyIcon icon="ant-design:clock-circle-outlined" />
        <span>最后更新: {{ monitoringData.timestamp }}</span>
        <Button type="link" size="small" @click="refreshData">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新
        </Button>
      </Space>
    </div>
  </div>
</template>

<style scoped>
.device-dashboard {
  padding: 16px;
}

.metrics-row {
  margin-bottom: 24px;
}

.metric-card {
  text-align: center;
}

.metric-status {
  margin-top: 8px;
}

.category-row {
  margin-bottom: 24px;
}

.category-card {
  text-align: center;
}

.category-header {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
}

.category-icon {
  font-size: 24px;
}

.category-name {
  font-size: 16px;
  font-weight: 500;
}

.category-stats {
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.stat-value {
  font-weight: 500;
}

.stat-value.online {
  color: #52c41a;
}

.stat-value.offline {
  color: #faad14;
}

.stat-value.error {
  color: #f5222d;
}

.category-progress {
  margin-top: 8px;
}

.monitoring-row {
  margin-bottom: 16px;
}

.alerts-card,
.performance-card {
  height: 300px;
}

.alerts-list {
  max-height: 200px;
  overflow-y: auto;
}

.alert-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.alert-item:last-child {
  border-bottom: none;
}

.alert-info {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 4px;
}

.alert-title {
  font-weight: 500;
}

.alert-details {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.alerts-footer {
  margin-top: 16px;
  text-align: center;
}

.performance-metrics {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.performance-item {
  margin-bottom: 16px;
}

.performance-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.performance-label {
  font-weight: 500;
}

.performance-value {
  font-weight: 600;
  color: #1890ff;
}

.update-time {
  font-size: 12px;
  color: #666;
  text-align: center;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-statistic-title) {
  font-size: 14px;
  color: #666;
}

:deep(.ant-statistic-content) {
  font-size: 24px;
  font-weight: 600;
}
</style>
